package 力扣._833_字符串中的查找和替换;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Solution {
    public String findReplaceString(String s, int[] indices, String[] sources, String[] targets) {
        //将index降序排序，这样会从后向前替换，不会影响下标
        List<Integer> ops = new ArrayList<>();
        for (int i = 0; i < indices.length; i++) {
            ops.add(i);
        }
        ops.sort(Comparator.comparingInt(i -> indices[i]));

        StringBuilder builder = new StringBuilder(s);

        for (int i = indices.length - 1; i >= 0; i--) {
            //真正的下标
            int t = ops.get(i);
            //index处是否存在sources【i】
            int k = builder.indexOf(sources[t], indices[t]);
            //如果存在,
            if (k == indices[t]) {
                builder.replace(indices[t], k + sources[t].length(), targets[t]);
            }
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        String s = new Solution().findReplaceString("abcd", new int[]{0, 2},
                new String[]{"a", "cd"}, new String[]{"eee", "ffff"});
        System.out.println(s);
    }
}
